using System;
using System.Net.Sockets;
using XcoAppSpaces.Transport.Sockets.Auth.Contract;
using System.Net;
using XcoAppSpaces.Transport.Sockets.Auth.Contract.DoServerHandshake;

namespace XcoAppSpaces.Transport.Sockets.Auth
{
	class ReceiveResponse : IReceiveResponse
	{
		//private int maxWaitForResponseSeconds;
		private string authenticationKey;
		
		public void In_Connection(ConnectionWithChallenge connection)
		{
			//Console.WriteLine("ReceiveResponse.In_Connection");
			try
			{
				var expectedResponse = ByteExtensions.CreateHash(connection.Challenge, authenticationKey);
				var stream = connection.Connection.Stream;
				var msg = NetworkStreamExtensions.ReadExactly(stream, expectedResponse.Length); 
				if (ByteExtensions.ArrayEquals(msg, expectedResponse))
				{
					stream.WriteByte(1);
					Out_ValidConnection(connection.Connection);
				}
				else
				{
					stream.WriteByte(0);
					Out_InvalidConnection(connection.Connection.Client);
				}
			}
			catch
			{
				Out_InvalidConnection(connection.Connection.Client);
			}
		}



		public event ValidConnectionHandler Out_ValidConnection;

        public event TcpClientHandler Out_InvalidConnection;

		public void Inject(SecuritySettings securitySettings)
		{
			//maxWaitForResponseSeconds = securitySettings.SecondsAfterInvalidConnectionIsClosed;
			authenticationKey = securitySettings.AuthenticationKey;
		}
	}
}
